﻿/*
    AddFriends for Kaixin001.com 

    Copyright (C) 2008, TurboZV, turbozv@gmail.com, http://www.turbozv.com/

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    *KEEP THIS HEADER INFORMATION*
*/

using System;
using System.Collections.ObjectModel;
using System.IO;
using Helper;
using System.Diagnostics;

namespace AddFriends
{
    public class AddFriends
    {
        public void Run()
        {
            ReadGlobalConfig();

            _newIdList.Clear();

            if (!File.Exists(c_NewFriendsFile))
            {
                TraceLog.Error("{0}文件不存在！", c_NewFriendsFile);
                return;
            }

            TraceLog.PrintLn("验证所有新号的账号和密码：");
            // 读取所有Id
            string[] newFriendsLines = File.ReadAllLines(c_NewFriendsFile);
            for (int i = 0; i + 1 < newFriendsLines.Length; i += 2)
            {
                int id = LogonAndGetId(newFriendsLines[i], newFriendsLines[i + 1]);
                if (-1 != id && !_newIdList.Contains(id))
                {
                    _newIdList.Add(id);
                }
            }

            string[] oldFriendsLines = new string[0];
            if (File.Exists(c_OldFriendsFile))  //可以不提供旧号的列表
            {
                TraceLog.PrintLn("验证所有旧号的账号和密码：");
                oldFriendsLines = File.ReadAllLines(c_OldFriendsFile);
                for (int i = 0; i + 1 < oldFriendsLines.Length; i += 2)
                {
                    int id = LogonAndGetId(oldFriendsLines[i], oldFriendsLines[i + 1]);
                    if (-1 != id && !_oldIdList.Contains(id))
                    {
                        _oldIdList.Add(id);
                    }
                }
            }

            TraceLog.PrintLn("");
            TraceLog.PrintLn("发送添加好友请求：");

            // 发送添加好友请求。老号登录去加所有新号
            for (int i = 0; i + 1 < oldFriendsLines.Length; i += 2)
            {
                Logon(oldFriendsLines[i], oldFriendsLines[i + 1]); // 逐个登录老号
                AddAllList(_newIdList);
            }

            // 发送添加好友请求。新号登录，互相加，再加老号
            for (int i = 0; i + 1 < newFriendsLines.Length; i += 2)
            {
                Logon(newFriendsLines[i], newFriendsLines[i + 1]); // 逐个登录新号
                AddAllList(_newIdList);
                AddAllList(_oldIdList);
            }

            TraceLog.PrintLn("");
            TraceLog.PrintLn("确认好友请求：");
            // 确认好友请求
            for (int i = 0; i + 1 < newFriendsLines.Length; i += 2)
            {
                Logon(newFriendsLines[i], newFriendsLines[i + 1]); // 逐个登录新号，确认好友请求
                ConfirmFriend();
            }

            TraceLog.PrintLn("");
            TraceLog.PrintLn("按任意键退出....");
            Console.ReadKey();
        }

        private void AddAllList(Collection<int> idList)
        {
            foreach (int id in idList)
            {
                SendFriendRequest(id);
            }
        }

        private bool SendFriendRequest(int id)
        {
            string postData = string.Format("from=&touid={0}&content=Hi", id);
            string content = _hh.Post("http://www.kaixin001.com/friend/addverify.php", postData);

            int pos;
            string name = ContentHelper.GetMidString(content, "你成功地将", "加为好友！", out pos);
            TraceLog.Print(string.Format("Add friend {0}({1}) :", name, id));
            if (content.IndexOf("var type = \"4\"") != -1)
            {
                TraceLog.PrintLn("Ok!");
                return true;
            }
            else
            {
                TraceLog.Error("Failed!");
                return false;
            }
        }

        private void ConfirmFriend()
        {
            int pos;
            string content = _hh.Get("http://www.kaixin001.com/msg/sys.php");

            //<div class="c9 mt5"  style="display:none;" id="divsysmsgclearall">共99条 <a href="javascript:clearSysMsg(0,'系统');" class="sl" title="清空全部系统消息">清空全部系统消息</a></div>
            string part = ContentHelper.GetMidString(content, "<div class=\"c9 mt5\"", "</div>", out pos); 
            string str = ContentHelper.GetMidString(part, ">共", "条", out pos);
            if (null == str)
            {
                return;
            }
            int totalPage = Int32.Parse(str) / 10;

            for (int page = 0; page <= totalPage; page++)
            {
                TraceLog.PrintLn("Page {0}/{1}", page, totalPage);
                //http://www.kaixin001.com/msg/sys.php?type=0&start=10
                content = _hh.Get("http://www.kaixin001.com/msg/sys.php?type=0&start=" + (page * 10).ToString());

                string v_fuid = ContentHelper.GetMidString(content, "javascript:agreefriend(", ",", out pos);
                if (null == v_fuid)
                {
                    continue;
                }
                content = content.Substring(pos);
                string v_smid = ContentHelper.GetMidString(content, " ", ")", out pos);
                while (null != v_fuid && null != v_smid)
                {
                    content = content.Substring(pos);

                    AgreeFriend(v_fuid, v_smid);

                    v_fuid = ContentHelper.GetMidString(content, "javascript:agreefriend(", ",", out pos);
                    if (null == v_fuid)
                    {
                        break;
                    }
                    content = content.Substring(pos);
                    v_smid = ContentHelper.GetMidString(content, " ", ")", out pos);
                }
            }
        }

        private void AgreeFriend(string v_fuid, string v_smid)
        {
            try
            {
                if (!_newIdList.Contains(Int32.Parse(v_fuid)) && !_oldIdList.Contains(Int32.Parse(v_fuid)))  // 不是我们要加的人，不理他
                {
                    return;
                }
                string postData = "fuid=" + v_fuid + "&byname=&memo=&groups=&allgroups=%E7%8E%B0%E5%9C%A8%E5%90%8C%E4%BA%8B%2C%E4%BB%A5%E5%89%8D%E5%90%8C%E4%BA%8B%2C%E5%A4%A7%E5%AD%A6%E5%90%8C%E5%AD%A6%2C%E9%AB%98%E4%B8%AD%E5%90%8C%E5%AD%A6%2C%E5%AE%B6%E4%BA%BA%E4%BA%B2%E6%88%9A%2C%E6%8C%9A%E4%BA%A4%E5%A5%BD%E5%8F%8B%2C%E6%99%AE%E9%80%9A%E6%9C%8B%E5%8F%8B%2C%E6%9C%8B%E5%8F%8B%E7%9A%84%E6%9C%8B%E5%8F%8B%2C%E5%85%B6%E4%BB%96&start=0&from=sysmsg&smid=" + v_smid;
                string content = _hh.Post("http://www.kaixin001.com/friend/editfriend.php", postData);
                TraceLog.PrintLn("Confirmed {0}!", v_fuid);
            }
            catch (OverflowException)
            {
            }
            catch (FormatException)
            {
            }
        }

        // 登录账号
        private bool Logon(string username, string password)
        {
            return LogonAndGetId(username, password) > 0;
        }

        // 登录账号 并获取用户 ID
        private int LogonAndGetId(string username, string password)
        {
            TraceLog.Print("Login as [{0}]: ", username);
            string content = _hh.Post("http://www.kaixin001.com/login/login.php", "url=%2F&email=" + HttpHelper.EncodePostData(username) + "&password=" + HttpHelper.EncodePostData(password));

            if (content.IndexOf("<title>我的首页 - 开心网</title>") != -1)
            {
                int pos;
                string strId = ContentHelper.GetMidString(content, "我的开心网ID:", "\"", out pos);
                int id = -1;
                if (strId != null)
                {
                    try
                    {
                        id = Int32.Parse(strId);
                    }
                    catch (OverflowException)
                    {
                    }
                    catch (FormatException)
                    {
                    }
                }
                TraceLog.PrintLn("Ok!, Id={0}", id);
                return id;
            }
            else
            {
                TraceLog.Error("Failed!");
                return -1;
            }
        }

        private void ReadGlobalConfig()
        {
            try
            {
                string dir = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
                string filename = dir + "\\" + c_ConfigFile;

                if (!File.Exists(filename))
                {
                    TraceLog.PrintLn("缺少{0}文件，系统加载默认配置.", filename);
                    return;
                }

                GlobalConfigData config = GlobalConfigHelper.ReadGlobalConfigData(filename);
                _hh.SetConfig(config);
                TraceLog.WriteToFile = config.WriteToLogFile;
            }
            catch (Exception e)
            {
                TraceLog.Error(e.Message);
            }
        }

        #region Member Fields
        private const string c_ConfigFile = "Config.txt";
        private const string c_NewFriendsFile = "NewFriends.txt";
        private const string c_OldFriendsFile = "OldFriends.txt";

        private Collection<int> _newIdList = new Collection<int>();
        private Collection<int> _oldIdList = new Collection<int>();
        private HttpHelper _hh = new HttpHelper();
        #endregion
    }
}
